<template>
  <div>
    <!-- 列表数据 -->
    <el-card class="content-card">
      <!-- 工具栏 -->
      <table-toolbar v-model:columns="columns"
                     v-model:size="size"
                     v-model:stripe="stripe"
                     @refresh="handleSearch">
        <!-- 操作区域 -->
        <el-button icon="Search" type="primary" plain round @click="handleSearch">{{ $t('form.search') }}</el-button>
        <el-button v-permission="'sys:menu:create'" type="primary"  round icon="Plus"  @click="handleFormShow(1, 0)">新增</el-button>
<!--        <el-button v-permission="'sys:menu:create'" icon="Remove" plain @click="handleCleanPermissionsCache">清理权限缓存</el-button>-->
      </table-toolbar>

      <!-- 列表记录 -->
      <div class="table-wrapper">
        <!-- 列表数据 -->
        <el-table ref="tableRef"
                  v-loading="loading"
                  :data="tableData"
                  :size="size"
                  :stripe="stripe"
                  row-key="id"
                  :tree-props="{ children: 'child', hasChildren: 'hasChildren' }"
                  show-overflow-tooltip>
          <template #empty>
            <el-empty class="table-empty" description="暂无数据"/>
          </template>

          <table-column :columns="columns">
            <template #title="scope">
              <span><SvgIcon :icon="scope.row.icon" style="margin-right: 6px"/>{{ scope.row.title }}</span>
            </template>

            <template #type="scope">
              <DictTag v-model="scope.row.type" dict-type="sys_menu_type" effect="plain"/>
            </template>

            <template #hidden="scope">
              <DictTag v-model="scope.row.hidden" :circle="false" dict-type="sys_hidden" effect="plain"/>
            </template>
            <template #status="scope">
              <DictTag v-model="scope.row.status" :circle="false" dict-type="sys_status" effect="plain"/>
            </template>

            <template #cache="scope">
              <DictTag v-model="scope.row.cache" :circle="false" dict-type="sys_yes_no" effect="plain"/>
            </template>

            <template #operations="scope">
              <el-space :size="1" :spacer="spacer">
                <el-button v-permission="'sys:menu:update'" link type="primary" @click="handleFormShow(2, scope.row.id)">编辑</el-button>
                <el-button v-permission="'sys:menu:delete'"  link type="danger" @click="handleSwitchStatus(scope.row)">删除</el-button>
              </el-space>
            </template>
          </table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 添加或修改用户对话框 -->
    <OperateForm ref="formRef" @refresh="handleSearch"/>
  </div>
</template>

<script lang="tsx" setup>
import { computed, h, onBeforeMount, reactive, ref } from 'vue';
import { QueryForm } from '@/components/query-form';
import useLoading from '@/hooks/use-loading';
import TableColumn, { TableColumnData } from '@/components/table-column/index.vue';
import TableToolbar from '@/components/table-toolbar/index.vue';
import { ElDivider, ElLoading, ElMessageBox, ElNotification, TableInstance } from 'element-plus';
import useTable from '@/hooks/use-table.ts';
import {
  sysMenuCleanPermissionsCache,
  sysMenuSwitchStatus,
  sysMenuTreeList,
  getMenuList,
  getMenuUpdate, getMenuDelete
} from '@/api/api-sys.ts';
import { hasPermission } from '@/utils/permission.ts';
import OperateForm from './SysMenuForm.vue';
import { SvgIcon } from '@/components/icon';
import { DictTag } from '@/components/dict-tag';
import { computedOperateWidth } from '@/utils';
import {timeStamp} from "@/utils/validate.ts";

defineOptions({name: 'sys-menu'});

const spacer = h(ElDivider, { direction: 'vertical' })

// 查询
const queryForm = reactive({
  name: undefined,
});
const queryFormRef = ref<InstanceType<typeof QueryForm>>();
const tableRef = ref<TableInstance>();
const tableData = ref<any[]>([]);

// 操作区域宽度计算
const operateWidth = computed(() => {
  let count = 0
  if (hasPermission('sys:menu:update')) count += 1
  if (hasPermission('sys:menu:delete')) count += 1
  return computedOperateWidth(count);
})

// 列设置
const columns = ref<TableColumnData[]>([
  {prop: 'title', label: '菜单名称', minWidth: 180, headerAlign: 'center'},
  {prop: 'sort', label: '排序', minWidth: 80, align: 'center'},
  {prop: 'type', label: '类型', minWidth: 90, align: 'center'},
  {prop: 'hidden', label: '可见', minWidth: 90, align: 'center'},
  {prop: 'status', label: '启用', minWidth: 90, align: 'center'},
  {prop: 'cache', label: '缓存', minWidth: 90, align: 'center'},
  {prop: 'path', label: '菜单路径', minWidth: 120, align: 'left'},
  {prop: 'name', label: '视图名称', minWidth: 120, align: 'left'},
  {prop: 'component', label: '菜单组件', minWidth: 200, align: 'left'},
  {prop: 'permissions', label: '授权标识', minWidth: 200, align: 'left'},
  {prop: 'create_time', label: '创建时间', width: 180, align: 'center',render: (scope, val) => <span>{timeStamp(val) || '-'}</span>},
  {prop: 'update_time', label: '修改时间', width: 180, align: 'center',render: (scope, val) => <span>{timeStamp(val) || '-'}</span>},
]);

onBeforeMount(() => {
  if (operateWidth.value > 0) {
    columns.value.push({prop: 'operations', label: '操作', fixed: 'right', width: operateWidth.value, align: 'left', headerAlign: 'center'},)
  }
});

const [loading, setLoading] = useLoading(false);
const {tableState} = useTable(() => fetchDataList(), queryFormRef, true);
const {size, stripe} = tableState;
const reverseWithChild=(arr:any)=> {
  return arr.slice().reverse().map(item => {
    if (Array.isArray(item.child)) {
      item.child = reverseWithChild(item.child);
    }
    return item;
  });
}
// 数据查询
const fetchDataList = async () => {
  setLoading(true);
  try {
    // 查询数据
    const {body} = await getMenuList({
      ...queryForm,
      action:'tree',
      plat:'client'
    });
    // 结果转换
    tableData.value =reverseWithChild(body);
  } catch (err) {
  } finally {

    setLoading(false);
  }
};

// 刷新数据
const handleSearch = () => {
  fetchDataList();
};

/** 添加/修改操作 */
const formRef = ref<any>()
const handleFormShow = (mode: number, id?: number) => {
  formRef.value.open(mode, id)
};

/** 状态切换 */
const handleSwitchStatus = (row: any) => {
  ElMessageBox({
    title: '提示',
    message: '是否确认进行此操作?',
    type: 'warning',
    showCancelButton: true,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  }).then((action) => {
    getMenuDelete({id:row.id,action:'delete'}).then(() => {
      ElNotification({title: '成功', message: '操作成功', type: 'success', duration: 2000})
      handleSearch()
    })
  }).catch(() => {

  });
};

// 清理权限缓存
const handleCleanPermissionsCache = () => {
  ElMessageBox({
    title: '提示',
    message: '是否确认清理后台权限缓存?',
    type: 'warning',
    showCancelButton: true,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  }).then((action) => {
    const loading = ElLoading.service({
      lock: true,
      text: '正在处理中...',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    sysMenuCleanPermissionsCache().then(() => {
      ElNotification({title: '成功', message: '操作成功', type: 'success', duration: 2000})
    }).finally(() => loading.close())
  }).catch(() => {

  });
};
</script>

<style lang="scss" scoped>

</style>
